package megalopolis.editor;

public class Controller {

	private Model model;

	private View view;

	public void setView(View view) {
		this.view = view;
	}

	public void setModel(Model model) {
		this.model = model;
	}

	private boolean checkModifiedAndContinue() {
		if (model.isModified()) {
			int ans = view.confirmDialog("Save changes?");
			switch (ans) {
				case View.CONFIRM_YES:
					saveFile();
				case View.CONFIRM_NO:
					return true;
				case View.CONFIRM_CANCEL:
					return false;
			}
		}
		return true;
	}

	public void log(Exception e) {
		e.printStackTrace();
		view.exceptionDialog(e);
	}

	///////////////////////////

	public void exit() {
		if (checkModifiedAndContinue()) {
			System.exit(0);
		}
	}

	public void newFile() {
		if (!checkModifiedAndContinue()) {
			return;
		}
		model.clear();
		view.modelUpdated(model);
	}

	public void loadFile() {
		if (!checkModifiedAndContinue()) {
			return;
		}
		String filename = view.loadFileDialog();
		if (filename == null) {
			return;
		}
		model.loadFromFile(filename);
		view.modelUpdated(model);
	}

	public void saveFile() {
		String filename = view.saveAsFileDialog();
		if (filename == null) {
			return;
		}
		model.saveToFile(filename);
		view.modelUpdated(model);
	}

}
